package com.gp.gback.system.common.mapping_support;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 16/11/17.
 */
public class HttpServletRequestWrapper4JsonToForm extends HttpServletRequestWrapper {
    private Map<String, String[]> map = null;

    private final byte[] buffer;

    @Override
    public String getParameter(String name) {
        return map.get(name) == null ? null : map.get(name)[0];
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return map;
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(map.keySet());
    }

    @Override
    public String[] getParameterValues(String name) {
        return map.get(name);
    }


    public HttpServletRequestWrapper4JsonToForm(HttpServletRequest request) throws IOException {
        super(request);
        buffer = readBytes(request.getInputStream());
        map = new HashMap<String, String[]>(request.getParameterMap());
        map.putAll(JsonUtil.jsonToMap(new ByteArrayInputStream(buffer)));
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }

        };
    }

    private static byte[] readBytes(InputStream in) throws IOException {
        BufferedInputStream bufin = new BufferedInputStream(in);
        int buffSize = 1024;
        ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize);

        byte[] temp = new byte[buffSize];
        int size = 0;
        while ((size = bufin.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        bufin.close();

        byte[] content = out.toByteArray();
        return content;
    }

}
